package com.inspur.resourcequery;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.inspur.common.BaseActivity;
import com.inspur.common.domain.RequestInfo;
import com.inspur.common.utils.URLManager;
import com.inspur.common.view.MyEditText;
import com.inspur.common.view.XListView;
import com.inspur.common.view.XListView.IXListViewListener;
import com.inspur.resourcequery.adapter.AttributeListAdapter;
import com.inspur.resourcequery.model.ResAttr;
import com.inspur.resourcequery.model.ResData;

public class AttributeListActivity extends BaseActivity implements IXListViewListener{
	// 自定义数据列表
	private XListView mListView = null;
	// 列表适配器
	private AttributeListAdapter adapter = null;
	// 搜索框
	private MyEditText mEditText = null;
	// 列表适配器中的数据项
	private List<ResAttr> list = new ArrayList<ResAttr>();
	// 分页查询起始项
	private int start = 0;
	// 每页加载数据量
	private int length = 15;
	// 数据总量
	private int totalCount;
	//总页数
	private int pageCount;
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	public ResData model;
	public ResAttr attribute;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		model = (ResData) getIntent().getSerializableExtra("model");
		attribute = (ResAttr) getIntent().getSerializableExtra("attribute");
		actionBar.setTitle(attribute.getAttributeCnName());
		
		mListView = (XListView)this.findViewById(R.id.xListView);
		adapter = new AttributeListAdapter(this, list);
		mListView.setAdapter(adapter);
		mListView.setXListViewListener(this);
		mListView.setPullLoadEnable(false);		
		mListView.setOnItemClickListener(itemClickListener);
		mEditText = (MyEditText)this.findViewById(R.id.search_met);
		mEditText.setOnEditorActionListener(searchListener);
		
		queryList();
	}
	
	/**
	 * 点击属性，数据回填
	 */
	OnItemClickListener itemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			
			Intent intent = new Intent();
			Bundle bundle = new Bundle();
			bundle.putSerializable("newAttr", list.get(position - 1) );
			intent.putExtras(bundle);
			AttributeListActivity.this.setResult(100, intent);
			AttributeListActivity.this.finish();
			
		}
	};
	
	
	OnEditorActionListener searchListener = new OnEditorActionListener() {
		
		@Override
		public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
			// TODO Auto-generated method stub
			if (actionId == EditorInfo.IME_ACTION_SEARCH) {
				//设置从第一条开始
				start = 0;
				queryList();
				
				//隐藏键盘
				InputMethodManager inputMethodManager = 
						(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
				inputMethodManager.hideSoftInputFromWindow(
						AttributeListActivity.this.getCurrentFocus().getWindowToken(),
						InputMethodManager.HIDE_NOT_ALWAYS);
				return true;
			}
			return false;
		}
	};
	
	/**
	 * 查询数据列表
	 */
	protected void queryList(){
		RequestInfo req = new RequestInfo();
		req.context = AttributeListActivity.this;
		req.requestUrl = URLManager.URL + URLManager.RES_QUERYATTRTRANS;
		try {
			JSONObject condition = new JSONObject();
			condition.put("ResClassName", model.getResclassenname());
			condition.put("parentColum", attribute.getParentColumn());
			condition.put("parentColumValue", attribute.getParentValue());
			condition.put("attributeenname", attribute.getAttributeEnName());
			condition.put("ifChange", attribute.getIfChange());
			condition.put("condition", mEditText.getText());
			condition.put("start", start);
			condition.put("limit", length);
			req.params=condition.toString();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		super.getDataFromServer(req, new DataCallback<String>() {
			@Override
			public void processData(String paramObject) {
				Log.d("paramObject:",paramObject);
				proccessData(paramObject);
			}

			@Override
			public void getDataFailed() {
				// 这里仅作演示，实际请求失败后怎么操作根据实际情况来看

			}

		}, AttributeListActivity.this);
	}
	
	public void proccessData(String paramObject){
		try {
			JSONObject jsonObj = new JSONObject(paramObject);
			totalCount = Integer.parseInt(jsonObj.getString("totalProperty"));
			JSONArray jsonArray = jsonObj.getJSONArray("root");
			if(start == 0){
				list.clear();
			}
			
			for(int i = 0; i < jsonArray.length(); i++){
				JSONObject attrObj = jsonArray.getJSONObject(i);
				ResAttr attr = new ResAttr();
				attr.setAttributeValue(attrObj.getString("id"));
				attr.setAttributeTransValue(attrObj.getString("name"));
				list.add(attr);
			}
			
			
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		adapter.notifyDataSetChanged();
		onLoad();
		
		if(start + length >= totalCount || attribute.getIfChange() != 1){
			mListView.setPullLoadEnable(false);
		} else {
			mListView.setPullLoadEnable(true);
		}
	}
	
	@Override
	public void onRefresh() {
		start = 0;
		queryList();
	}

	@Override
	public void onLoadMore() {
		start = start + length;
		queryList();
	}

	private void onLoad() {
		mListView.stopRefresh();
		mListView.stopLoadMore();
		mListView.setRefreshTime(sdf.format(new Date()));
	}

	@Override
	protected void loadViewLayout() {
		// TODO Auto-generated method stub
		setContentView(R.layout.activity_attribute_list);
	}

	@Override
	protected void findViewById() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void setListener() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processLogic() {
		// TODO Auto-generated method stub

	}

}
